package com.diamond.service.impl;

import com.diamond.service.KettleService;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Iterator;
import java.util.Map;

@Service
public class KettleServiceImpl implements KettleService {
    @Value("${kettle.script.path}")
    private String dirPath;

    public void runKtr(String filename, Map<String, String> params) {
        try {
                // 初始化
                KettleEnvironment.init();
                TransMeta tm = new TransMeta(dirPath + File.separator + filename);
                Trans trans = new Trans(tm);
                // 设置参数
                if (params != null) {
                    Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry<String, String> entry = entries.next();
                        trans.setParameterValue(entry.getKey(),entry.getValue());
                    }
                }
                trans.execute(null);
                trans.waitUntilFinished();
                if(trans.getErrors()>0){
                    System.out.println("出错了");
                }else{
                    System.out.println("未出错");
                }
        }catch (Exception e){
            System.out.println("执行转换异常");
        }
    }

    public void runKjb(String filename, Map<String, String> params) {
        try{
            KettleEnvironment.init();
            JobMeta jm = new JobMeta(dirPath + File.separator + filename, null);
            Job job = new Job(null, jm);
            if (params != null) {
                Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, String> entry = entries.next();
                    job.setVariable(entry.getKey(), entry.getValue());
                }
            }
            job.start();
            job.waitUntilFinished();
        }catch (Exception e){
            System.out.println("执行job异常");
        }
    }
}
